/*
 * @description:
 * @version: 1.0.1
 * @Author: xuqiulin
 * @Date: 2021-04-28 11:34:51
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-04-28 21:05:33
 */
package main

import (
	"fmt"
	"log"
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Animal struct {
	Id   bson.ObjectId `bson:"_id" json:"id"`
	Name string        `bson:"Name" json:"Name"`
	Age  int64         `bson:"Age" json:"Age"`
	Time int64         `bson:"Time" json:"Time"`
}

func main() {
	// 连接数据库
	session, err := mgo.Dial("192.168.2.218:27017")
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)
	// 获取server_4000数据库的Animal集合
	c := session.DB("server_4000").C("Animal")
	// 向集合中插入数据
	err = c.Insert(
		&Animal{Id: bson.NewObjectId(), Name: "小昆虫", Age: 100, Time: time.Now().Unix()},
		&Animal{Id: bson.NewObjectId(), Name: "爱白菜", Age: 200, Time: time.Now().Unix()},
	)
	if err != nil {
		log.Fatal(err)
	}
	// 查找名字爱白菜的数据
	animal := Animal{}
	err = c.Find(bson.M{"Name": "爱白菜"}).One(&animal)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", animal)
}
